﻿using Microsoft.AspNetCore.SignalR;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Powerpi.Hubs
{
    /// <summary>
    /// 服务端接口
    /// </summary>
    public interface IServerNotifyHub
    {
        Task SendMessage(string message);
    }

    /// <summary>
    /// 客户端使用的接口
    /// </summary>
    public interface IClientNotifyHub
    {
        Task OnNotify(object data);

        Task OnLine(object data);

        Task OffLine(object data);
    }
    public class ClockHub : Hub, IServerNotifyHub
    {
        /// <summary>
        /// 建立连接时触发
        /// </summary>
        /// <returns></returns>
        public override async Task OnConnectedAsync()
        {
            Console.WriteLine($"ConnectionId = {Context.ConnectionId}");
            await NotifySend($"{Context.ConnectionId}已连接");
            await base.OnConnectedAsync();

        }

        /// <summary>
        /// 离开连接时触发
        /// </summary>
        /// <param name="ex"></param>
        /// <returns></returns>
        public override async Task OnDisconnectedAsync(Exception ex)
        {
            Console.WriteLine($"Connector[{Context.ConnectionId}]已断开连接,异常：{ex?.Message}");
            await base.OnDisconnectedAsync(ex);
        }

        public async Task SendMessage(string message)
        {
            await NotifySend(message);
        }

        /// <summary>
        /// 向所有人推送消息
        /// </summary>
        /// <param name="message"></param>
        /// <returns></returns>
        private Task NotifySend(string message)
        {
            return Clients.All.SendAsync("notify", $"{message}");
        }
    }
}
